import path from 'path'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import setupExtend from 'vite-plugin-vue-setup-extend'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createHtmlPlugin } from 'vite-plugin-html'
import topLevelAwait from 'vite-plugin-top-level-await'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import { viteMockServe } from 'vite-plugin-mock'

export default function createVitePlugins(viteEnv: Record<string, string>, isBuild = false) {
  const { VITE_GLOB_APP_TITLE } = viteEnv
  const vitePlugins = [
    vue(),
    nodePolyfills(),
    setupExtend(),
    createSvgIconsPlugin({
      // 指定需要缓存的图际文件夹
      iconDirs: [path.resolve(process.cwd()), 'src/assets/icons/svg'],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]'
    }),
    Components({
      resolvers: [ElementPlusResolver()]
    }),
    AutoImport({
      // include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md%/],
      include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/],
      imports: [
        // 插件预设支持的api
        'vue',
        'vue-router',
        'pinia'
      ],
      eslintrc: {
        enabled: false, // 默认false, true启用. 生成一次就可以, 避免每次工程启动都生成
        filepath: './.eslintrc-auto-import.json',
        globalsPropValue: true
      },
      dts: './auto-imports.d.ts',
    }),
    createHtmlPlugin({
      minify: isBuild,
      inject: {
        data: {
          title: VITE_GLOB_APP_TITLE
        }
      }
    }),
    topLevelAwait({
      promiseExportName: '__tla',
      promiseImportName: i => `__tla_${i}`
    }),
    viteMockServe({
      mockPath:  path.resolve(__dirname, './mock'),
      enable: true
    })
  ]

  return vitePlugins
}
